<template>
  <base-modal v-loading="loading" :title="title" width="500px"  :unique="unique" :top="top" :show.sync="visible" :append-to-body="appendToBody" class="task-plantime-dialog">
    <div class="base-modal-content plantime-dialog-content">
      <form-item :label="field.displayName" v-if="field.id && modifiable">
        <form-plantime :picker-options="planTimeDatePickeroptions" :field="field" :value="planTime" @update="update"></form-plantime>
      </form-item>
      <el-checkbox class="task-planTime-notice" v-model="sendSMS" v-if="(action == 'modifyPlanTime'||action == 'modifyPlanStartTime'||action == 'modifyPlanEndTime') && enableSendSms">{{$t('task.sendSmsNotice')}}</el-checkbox>
      <!--      -->
      <div class="task-initiate-plan-dialog-form">
        <form-builder
          class="bbx-cell-form-builder"
          ref="taskCustomeCalendarRef"
          mode="taskCustomeCalendar"
          formStatus="edit"
          formEditingMode="edit"
          :fields="acceptFields"
          :value="formValue"
          @getDeleteFiles="getDeleteFiles"
          @update="updateForm"
        >
        </form-builder>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button v-if="showAcceptForm" :disabled="pending"  @click="toTemporaryStorage">{{ $t('common.base.temporaryStorage') }}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{ action === 'acceptFromPool' ? $t('common.task.button.acceptFromPool') : $t('common.base.makeSure') }}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

/* util */
import { safeNewDate } from '@src/util/time';
import { isDevelopment } from '@src/util/platform';
import { RESOURCE_PREFIX } from '@src/util/linkSwitch';
import {getTimestamp, dayTimeStart, useFormTimezone} from 'pub-bbx-utils';
import { getRootWindow } from "@src/util/dom";
import {draftSaveCustomerNode, getCurrentDraftCustomerNode, getTaskCustomNodeFields} from "@src/api/TaskApi.ts";
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'
import _ from "lodash";
import * as FormUtil from "@form/util";
const resourcePrefix = isDevelopment() ? '' : RESOURCE_PREFIX
const { disposeFormSubmitTime } = useFormTimezone()

export default {
  name: 'plantime-dialog',
  props: {
    task: {
      type: Object,
      default: () => ({})
    },
    field: {
      type: Object,
      default: () => ({})
    },
    // 工单设置修改计划时间开关
    modifiable: {
      type: Boolean,
      default: true
    },
    successCallback: {
      type: Function,
      default() {
        window.location.href = `${resourcePrefix}/task/view/${this.task.id}`
      }
    },
    enableSendSms: {
      type: Boolean,
      default: true
    },
    top: {
      type: Boolean,
      default: false
    },
    unique: {
      type: Boolean,
      default: true
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
  },
  data: () => {
    return {
      type: '',
      visible: false,
      pending: false,
      action: '',
      planTime: '',
      sendSMS: false,
      planTimeDatePickeroptions: {
        disabledDate(time) {
          return time.getTime() < safeNewDate(safeNewDate().toLocaleDateString()).getTime()
        }
      },
      acceptFields: [], // 接单节点配置的自定义字段
      formValue: {},
      needServerDelFiles: [],
      title: '',
      loading: false,
      temporaryStorageVal: {},
    }
  },
  computed: {
    dateType() {
      return this.field?.setting?.dateType
    },
    // 工单节点拓展灰度
    taskFlowExtend() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
    },
    // 接单节点是否有字段
    showAcceptForm() {
      return this.acceptFields?.length ?? false
    },
    // 判断是否显示计划时间
    showPlanTime() {
      return this.field?.id && this.modifiable
    }
  },
  methods: {
    // 删除的附件
    getDeleteFiles(files) {
      this.needServerDelFiles = [...this.needServerDelFiles, ...files]
    },
    // 更新表单字段
    updateForm({ field, newValue }) {
      if(!field) return
      const { fieldName = '' } = field || {};

      this.$set(this.formValue, fieldName, newValue);
    },
    /**
    * @description 更新计划时间
    */
    update({ field, newValue, oldValue }) {
      this.$set(this, 'planTime', newValue);
    },
    // 接单前判断是否 1.接单节点是否配置了自定义字段
    async beforeOpenForAccept(action) {
      try {
        this.loading = true;
        let acceptFields = []
        // 判断接单接单有没有开启节点灰度，开启了需要查询配置表单
        if(this.taskFlowExtend) {
          const res = await getTaskCustomNodeFields({ taskId: this.task.id });
          acceptFields  = res?.result ?? []
          // 接单表单有字段，如果不允许修改计划时间（modifiable）,但是计划时间的值是空的，需要提示请先填写计划时间
          const name = this.field.formType || this.field.name || this.field.fieldName;
          const planTime = getTimestamp(this.task[name] || '');
          if (!planTime && !this.modifiable ) return this.$platform.alert(this.$t('task.tip.pleaseFillInSth', {content: this.field.displayName}));
          // 获取暂存的字段值
          const { success = false, result = {} } = await getCurrentDraftCustomerNode({ taskId: this.task.id, currentNodeId: 'accept' })
          if(success) this.temporaryStorageVal = result?.formData ?? {}
        }
        this.acceptFields = acceptFields;
        // 获取引用字段值
        const val = _.cloneDeep(this.task.attribute)
        let formDate = {};
        this.acceptFields?.forEach(item => {
          if(item.fieldName in this.temporaryStorageVal) {
            this.$set(formDate, item.fieldName, this.temporaryStorageVal[item.fieldName])
          }else {
            val?.[item.fieldName] && this.$set(formDate, item.fieldName, val[item.fieldName])
          }
        })
        this.formValue = FormUtil.initialize(this.formField, formDate);

        await this.openDialog(action)
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false;
      }
    },
    /**
    * @description 打开计划时间弹窗
    */
    async openDialog(action = 'modifyPlanTime', type) {
      this.type = type;// 用于区分是修改计划开始还是计划完成时间
      this.action = action;
      if(this.field){
        // 数据兼容
        const name = this.field.formType || this.field.name || this.field.fieldName;
        this.planTime =  ('planTime' in this.temporaryStorageVal) ? (this.temporaryStorageVal?.planTime || '') : getTimestamp(this.task[name] || '');
        // 计划时间为必填
        if(this.field.formType === 'planTime') {
          this.field.isNull = 0
        }
        
        if (!this.modifiable && !this.acceptFields?.length) {
          this.submit();
          return;
        }
      }
      if(this.showPlanTime) {
        this.title = this.$t('task.detail.components.adjustSth', {data: this.field.displayName})
      }else {
        this.title = this.$t('common.task.acceptTitle')
      }
      this.sendSMS = false;
      this.visible = true;
    },
    submit() {
      if (this.pending) return;
      if (!this.planTime) return this.$platform.alert(this.$t('task.tip.pleaseFillInSth', {content: this.field.displayName}));

      // 校验计划时间是否早于当前时间
      let planTime = getTimestamp(this.planTime);
      if(this.modifiable){
        if (this.dateType === 'dateTime') {
          let nowTime = +new Date();
          if (planTime < nowTime) return this.$platform.alert(this.$t('task.tip.planTimeTip3', {data: this.field.displayName}));
        }
        if(this.field.formType === 'planStartTime' && this.task.planEndTime){
          let endTime = getTimestamp(this.task.planEndTime); 
          if (planTime > endTime) return this.$platform.alert(this.$t('task.tip.planTimeTip2'));
        }
        if(this.field.formType === 'planEndTime' && this.task.planStartTime){
          let startTime = getTimestamp(this.task.planStartTime);
          if (planTime < startTime) return this.$platform.alert(this.$t('task.tip.planTimeTip4'));
        }
      }
      
      let newPlanTime = this.dateType === 'date' ? +dayTimeStart(this.planTime) : planTime;
      
      const { 
        task,
        type,
        action,
      } = this
      let params = { 
        taskId: task.id,
        [type || 'newPlanTime']: newPlanTime,
      };

      // 修改计划时间时参数
      let _action = action
      if (action === 'modifyPlanTime' || action === 'modifyPlanStartTime' || action === 'modifyPlanEndTime') {
        _action = 'modifyPlanTime';
        params.planTime = newPlanTime;
        params.sendSMS = this.sendSMS;
        if(action === 'modifyPlanStartTime'){
          params.timeType = 1;
        }
        if(action === 'modifyPlanEndTime'){
          params.timeType = 2;
        }
        delete params.newPlanTime;
      }

      if(this.showAcceptForm) {
        params.formData = disposeFormSubmitTime(this.acceptFields, this.formValue) // 处理国际化时间转换
        params.needServerDelFiles = this.needServerDelFiles;
      }

      this.pending = true;

      TaskApi[_action](params)
        .then(res => {
          if (res.success) {
            if(['acceptFromPool', 'accept'].includes(action)) {
              this.$track.clickStat(this.$track.formatParams('ACCEPT_TASK_SUCCESS'));
            }

            this.visible = false
            this.successCallback(newPlanTime)
          } else {
            this.$platform.alert(res.message);
            this.pending = false;
          }
        })
        .catch(err => {
          this.pending = false;
        })
        .finally(() => {
          this.pending = false
        })
    },

    /*暂存表单*/
    async toTemporaryStorage() {
      try {
        this.pending = true;

        let formData = disposeFormSubmitTime(this.acceptFields, this.formValue) // 处理国际化时间转换

        formData = {
          ...formData,
          planTime: getTimestamp(this.planTime),
        }

        const params = {
          taskId: this.task.id,
          currentNodeId: 'accept',
          formData,
        }
        const { success, message } = await draftSaveCustomerNode(params)

        if(!success) return this.$message.error(message);

        this.$message.success(this.$t('common.base.temporarySaveSuccess'));

        this.visible = false;
      } catch (e) {
        console.error(e)
      } finally {
        this.pending = false;
      }
    },
  }
}
</script>

<style lang="scss">
.task-plantime-dialog {
  .form-item {
    margin-bottom: 6px;
    
    & > label {
      width: auto !important;
      padding-left: 0;
      margin-right: 20px;
    }
  }
  
  .task-planTime-notice {
    margin-bottom: 0;
  }
  .plantime-dialog-content .form-datetime {
    width: 100% !important;
  }
}
.plantime-dialog-content {
  padding: 0 !important;
}
</style>
<style lang="scss">
.task-initiate-plan-dialog-form {
  .form-builder {
    padding: 0 !important;
    width: 100% !important;

    .form-item {
      padding-left: 0 !important;
    }
  }
}
</style>
